UIOfflineRewards = {};
HelperFunc.SetUIEnv(UIOfflineRewards)
local this = UIOfflineRewards;

this.listItem = nil;
this.txt_offline = nil;
this.btn_get = nil;
this.btn_close = nil;
this.templist = {};

this.rewarddata = nil;
this.itemList = {}
-- this.gameObject = nil
this.imgPlayExpIcon = nil;
this.txtPlayExpOutput = nil;
this.imgHeroExpIcon = nil;
this.txtHeroExpOutput = nil;
this.imgGoldIcon = nil;
this.txtGoldtOutput = nil;
this.btnDropInfo=nil

function UIOfflineRewards.Init(rewardinfo)
    rewarddata = rewardinfo
    local name, packageName = getUIName(PanelNames.UIOfflineRewards);
    panelMgr:Push(name, packageName, this.OnCreate, Config.useLocalUI);
end

function UIOfflineRewards.OnCreate(obj)
    -- gameObject = obj
    if this.haveInit ~= true then
        this.haveInit = true
        listItem = obj:GetChild("listItem")
        this.txt_offline = obj:GetChild("time")
    
        --------------------------------------------------------
        -- 掠夺相关
        this.plunder_type_controller = obj:GetController("type")
        this.list_rob_head = obj:GetChild("LIst_RobHead")
        this.list_rob_head.itemRenderer = this.itemRendererRobHead
        this.list_rob_head.numItems = 0
        this.txt_rob = obj:GetChild("Text_rob")
        this.btn_rob = obj:GetChild("Text_Revenge")
        ------------------------------------------------------

        this.btn_get = obj:GetChild("GetBtn")
        this.btn_close = obj:GetChild("BgClose");

        local PlayExpGroup = obj:GetChild("PlayExpGroup");
        imgPlayExpIcon = PlayExpGroup:GetChild("Icon");
        txtPlayExpName = PlayExpGroup:GetChild("Name");
        txtPlayExpOutput = PlayExpGroup:GetChild("Output");
        local HeroExpGroup = obj:GetChild("HeroExpGroup");
        imgHeroExpIcon = HeroExpGroup:GetChild("Icon");
        txtHeroExpName = HeroExpGroup:GetChild("Name");
        txtHeroExpOutput = HeroExpGroup:GetChild("Output");
        local GoldGroup = obj:GetChild("GoldGroup");
        imgGoldIcon = GoldGroup:GetChild("Icon");
        txtGoldName = GoldGroup:GetChild("Name");
        txtGoldtOutput = GoldGroup:GetChild("Output");

        this.rewardCtrl = obj:GetController("reward");
        this.rewardCtrl.selectedIndex = 0
        btnDropInfo=obj:GetChild("Btn_Dropinfo")
        btnDropInfo.onClick:Add(this.OnClickDropInfo)
        logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIOfflineRewards,Config.FuncOpenType.HangupPreView,btnDropInfo.name,btnDropInfo)

        this.btn_get.onClick:Add(this.onClickReward);
        this.btn_close.onClick:Add(this.onClickReward);
    end

    this.InitAwardTimer()
    this.SetInfo()
    this.RefreshEXP()
end

function UIOfflineRewards.GetTimeStr(time,maxTime)
    if time > maxTime then
        time = maxTime
    end
    return timeToTimeFormat(time)
end

function UIOfflineRewards.InitAwardTimer()
    this.DestoryTimer()
    this.cur_plunders = {}
    local time = rewarddata.seconds
    local maxTime = logicMgr.HeroManager.getSettleingMaxTime()
    this.txt_offline.text = this.GetTimeStr(time,maxTime)
    this.timer = utimer.timeCall(function( ... )
        time = time + 1
        if this.txt_offline ~= nil then
            this.txt_offline.text = this.GetTimeStr(time, maxTime)
        end
    end, 1000, -1) 

    local plunders = rewarddata.plunders     
    if plunders ~= nil and next(plunders) ~= nil then
        this.plunder_type_controller:SetSelectedIndex(1)
        this.initPlundersData( plunders )
    else
        this.plunder_type_controller:SetSelectedIndex(0)
    end 
 
end

function UIOfflineRewards.initPlundersData( plunders )
    
    this.cur_plunders = plunders or {}
    local num = #this.cur_plunders
    this.list_rob_head.numItems = num or 0

    if num == 1 then
        this.list_rob_head.x = 455
    elseif num == 2 then
        this.list_rob_head.x = 366 
    elseif num == 3 then
        this.list_rob_head.x = 278 
    elseif num == 4 then
        this.list_rob_head.x = 190 
    else
        this.list_rob_head.x = 107
    end

    local count = 0
    for _, v in pairs(this.cur_plunders) do
        count = count + (v.plunderPer or 0)
    end

    count = count/100
    if count == 0 then
        count = 0.01
    end

    this.txt_rob.text = string.format(getLanguage("RogueTips05"), count.."%")
    this.btn_rob.onClick:Add(function() 
        showUI(PanelNames.UIBigMap, plunderHandler.have_search) 
        -- showUI(PanelNames.UIRevengeRecord) 
        showUI(PanelNames.UIRevengeRecord, 2)
        closeUI(PanelNames.UIOfflineRewards)
    end)
end

function UIOfflineRewards.itemRendererRobHead(index, obj)
  
    local head_frame = obj:GetChild("frame")
    local head = obj:GetChild("head")
    local head_icon = head:GetChild("HeadIcon")

    local item_info = this.cur_plunders[index+1]
    if item_info then
        if head_frame then
            head_frame.url = EnumConst.AtlasPath.ICONAtlas .. item_info.picFrame
        end
        if head_icon then
            head_icon.url = logicMgr.SkinManager.GetHeroIconBySkinId(item_info.pic)--EnumConst.AtlasPath.ICONAtlas .."icon_hero_".. item_info.pic
        end
        obj.onClick:Clear()
        obj.onClick:Add(function()
            --showUI(PanelNames.UIBigMap, plunderHandler.have_search)
            -- showUI(PanelNames.UIRevengeRecord) 
            showUI(PanelNames.UIRevengeRecord, 2)
            closeUI(PanelNames.UIOfflineRewards)
        end)
    end
end


function UIOfflineRewards.RefreshEXP()
    local mapId = logicMgr.MapManager.getMapId();
    if mapId == 0 then
        mapId = 101;
    end
    --刷新函数
    local curMap = dataTable.getDataTableByStringId("t_stage",mapId);
    local itemConfig = dataTable.getDataTable("t_item")
    local playExpConfig = itemConfig[tostring(CurrencyEnum.RoleExp)]
    imgPlayExpIcon.url = "ui://ItemAtlas/"..playExpConfig.f_Icon;
    local timeUnit = getLanguage("Sys_OutPut")
    local power = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineRatio, playExpConfig.f_itemModelId);
    local power2 = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineFix, playExpConfig.f_itemModelId);
    txtPlayExpOutput.text = Mathf.Round(curMap.f_Exp * (1 + power*0.0001) + power2 / 1440) .. timeUnit;
    local HeroExpConfig = itemConfig[tostring(CurrencyEnum.HeroExp)];
    imgHeroExpIcon.url ="ui://ItemAtlas/".. HeroExpConfig.f_Icon;
    power = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineRatio, HeroExpConfig.f_itemModelId);
    power2 = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineFix, HeroExpConfig.f_itemModelId);
    txtHeroExpOutput.text = Mathf.Round(curMap.f_HeroExp * (1 + power*0.0001) + power2 / 1440) .. timeUnit;
    local goldConfig = itemConfig[tostring(CurrencyEnum.MONEY)];
    imgGoldIcon.url = "ui://ItemAtlas/".. goldConfig.f_Icon;
    power = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineRatio, goldConfig.f_itemModelId);
    power2 = logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.OffLineFix, goldConfig.f_itemModelId);
    txtGoldtOutput.text = Mathf.Round(curMap.f_Coin * (1 + power*0.0001) + power2 / 1440) .. timeUnit;
end
function UIOfflineRewards.SetInfo()
    itemList = {}
    if rewarddata == nil then
        return;
    end
    local scoreSequence = DOTween.Sequence();
    scoreSequence:SetAutoKill(false);

    local allitems = rewarddata.items;
    --[[local testItem = {}
    testItem = {
        icon = "300100",
        itemModelId = 300100,
        name = "随机N品质装备",
        num = 2,
        quality = 7,
    }
    table.insert(allitems,testItem)]]
    templist = {};
    local count = 0;
    for i=1,#allitems do
        local num = tonumber(tostring(allitems[i].num))
        if num>0 then
            local isHave,index = this.WardIsHave(allitems[i].itemModelId)
            if isHave then
                templist[index].num = templist[index].num + num
            else
                local data = {};
                data["itemModelId"] = allitems[i].itemModelId;
                data["num"] = num;
                data["quality"] = allitems[i].quality;
                data["icon"] = allitems[i].icon;
                data["level"] = allitems[i].level;
                data["name"] = allitems[i].name;
                if logicMgr.ItemManager.getItemTabType(allitems[i].itemModelId) == EnumConst.ItemTableEnum.Equip then
                    data["itemType"] = EnumConst.ItemTypeEnum.Equip;
                else
                    local da = logicMgr.ItemManager.getItemConstDatabyModelId(allitems[i].itemModelId);
                    data["desc"] = da.desc;
                    data["itemType"] = da.itemType;
                end

                table.insert(templist,data);
                count = count + num;

                table.insert(itemList, data["itemModelId"])
            end
        end
    end
    listItem.itemRenderer = this.setData;
    local num = #templist
    listItem.numItems = num
    HelperFunc.ListTranstionPlay(listItem)
    this.rewardCtrl.selectedIndex = num > 0 and 0 or 1 --on off
    --listItem:setDataByJsonArray(getJsonStr(templist));
end

function UIOfflineRewards.WardIsHave(itemModelId)
    local isHave
    local idenx
    for k,v in pairs(itemList) do
        if v == itemModelId then
            isHave = true
            idenx = k
            break
        end
    end
    return isHave,idenx
end

function UIOfflineRewards.setData(index,obj)
    local itemdata = templist[index + 1];
    local item = CtrlManager.GetCtrl(PanelNames.Item);
    item.initData(obj,itemdata);
    this.AddDefaultClick(obj, itemdata);
end

function UIOfflineRewards.AddDefaultClick(icon, data, isBag)
    icon.onClick:Clear();
    icon.onClick:Add(function()
        data["isBag"] = false
        showUI(PanelNames.UIBagItemInfo, data)
    end)
    
end

function UIOfflineRewards.OnDisable()
    this.DestoryTimer()
end

function UIOfflineRewards.OnDestroy()
    this.DestoryTimer()
    this.haveInit = nil
    if this.btn_rob then
        this.btn_rob.onClick:Clear()
        this.btn_rob = nil
    end
    if this.btn_get then
        this.btn_get.onClick:Clear()
        this.btn_get = nil
    end
    if this.btn_close then
        this.btn_close.onClick:Clear()
        this.btn_close = nil
    end 
    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIOfflineRewards);
end

function UIOfflineRewards.DestoryTimer()
    if this.timer then
        utimer.remove(this.timer)
        this.timer = nil
    end
end

function UIOfflineRewards.OnClickDropInfo()
    showUI(PanelNames.UIDropInfo);
end

function UIOfflineRewards.onClickReward()
    closeUI(PanelNames.UIOfflineRewards);
    local msg = {};
    msg["itemList"] = itemList;
    FireEvent(Config.EventType.Get_DropAward,msg);
    --播放挂机获得道具音效
    for _, itemModelId in ipairs(this.itemList) do
        AudioManager.TryPlaySoundItemChange(itemModelId,true)
    end

    if logicMgr.HeroManager.GetLastPlayerLevel() ~= logicMgr.HeroManager.GetRoleLevel() then
        logicMgr.GuideMgr.Pause()
        showUI(PanelNames.UICommonLevelUp, logicMgr.HeroManager.GetLastPlayerLevel(), logicMgr.HeroManager.GetRoleLevel(),
                function ()
                    logicMgr.GuideMgr.Resume()
                    if not logicMgr.GuideMgr.IsGuiding() then
                        logicMgr.FlashGiftManager.showNewFlashGift();
                    end
                end
        );
        logicMgr.HeroManager.SetLastPlayerLevel(logicMgr.HeroManager.GetRoleLevel());
        logicMgr.UnlockFuncManager.updateUnlockFunc(); -- 解锁功能，发起协议
    end
end

return UIOfflineRewards;